//
//  RunningInformationVC.m
//  KEREN
//
//  Created by MW on 2023/4/4.
//

#import "RunningInformationVC.h"
#import "ArcLineView.h"
#import "KeRenHCollectCell.h"
@interface RunningInformationVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UICollectionView *collectionV;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSDictionary *operationInfo;
@property (nonatomic, strong) UILabel *capacityLb;
@property (nonatomic, strong) UILabel *batteryLb;
@property (nonatomic, assign) BOOL connecting;
@end

@implementation RunningInformationVC
-(UICollectionView *)collectionV{
    if(!_collectionV){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsZero;
        _collectionV = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionV.delegate = self;
        _collectionV.dataSource = self;
        _collectionV.showsHorizontalScrollIndicator = NO;
        _collectionV.showsVerticalScrollIndicator   = NO;
        _collectionV.backgroundColor = [UIColor clearColor];
        [_collectionV registerNib:[UINib nibWithNibName:@"KeRenHCollectCell" bundle:nil] forCellWithReuseIdentifier:@"KeRenHCollectCell"];
    }
    return _collectionV;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"运行信息"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blueVerifySuccess) name:BLUETOOTHVERIFYSUCCESS object:nil];
    self.operationInfo = @{};
    
    self.dataArray = @[].mutableCopy;
    SmartItem *item;
    if(self.deviceInfo.deviceConfig.gps){
        item = [SmartItem createSmartItem:@"车辆GPS" imgName:@"device_state" type:SmartType_GPS];
        [self.dataArray addObject:item];
    }else{
        if(!self.deviceInfo.deviceConfig.fourg){
            item = [SmartItem createSmartItem:@"" imgName:@"device_info_left_empty" type:SmartType_Connect_Empty];
            [self.dataArray addObject:item];
        }
    }
    item = [SmartItem createSmartItem:@"蓝牙连接" imgName:@"device_ble" type:SmartType_BlueTooth];
    [self.dataArray addObject:item];
    
    if(self.deviceInfo.deviceConfig.fourg){
        item = [SmartItem createSmartItem:@"4G连接" imgName:@"device_4G" type:SmartType_4G];
        [self.dataArray addObject:item];
    }else{
        if(!self.deviceInfo.deviceConfig.gps){
            item = [SmartItem createSmartItem:@"" imgName:@"device_info_right_empty" type:SmartType_Connect_Empty];
            [self.dataArray addObject:item];
        }
    }
   
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,  56 + STATUSBAR_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - 56 + STATUSBAR_HEIGHT)];
    [self.view addSubview:_scrollView];
    [self setViewLayout];
    [self getOperationInfo];
}

- (void)setViewLayout{
    
    UIView *informationView = [[UIView alloc] initWithFrame:CGRectMake(24, 20, DEVICE_WIDTH - 48, 456/4)];
        [_scrollView addSubview:informationView];
    informationView.backgroundColor = UIColor.whiteColor;
    informationView.layer.cornerRadius = 25;
    informationView.clipsToBounds = YES;
    NSArray *titleArr = @[@"电池容量",@"电池电量"];
    if([UserInfoManager sharedInstance].currentDeviceInfo.battery_type != 1){
        titleArr = @[@"电池容量"];
    }
    NSArray *imageArr = @[@"device_cell_state",@"devce_cell_date"];
    for (int i = 0; i < titleArr.count; i ++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(i % 2 * (DEVICE_WIDTH - 48) / 2, i/2 * 456 / 4, (DEVICE_WIDTH - 48) / 2, 456 / 4)];
        view.backgroundColor = [UIColor whiteColor];
        [informationView addSubview:view];
        UIImageView *iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageArr[i]]];
        [view addSubview:iconImageView];
        [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.width.height.offset(24);
            make.top.offset(24);
        }];
        UILabel *titleLbl = [UILabel setLblText:titleArr[i] font:Font(14) withColor:Color_86898E inSubView:view];
        [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(iconImageView);
            make.left.equalTo(iconImageView.mas_right).offset(4);
        }];
        UILabel *decLbl = [UILabel setLblText:@"" font:Font(36) withColor:Black_Color inSubView:view];
        [decLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.top.equalTo(titleLbl.mas_bottom).offset(10);
        }];
        if(i == 0){
            self.capacityLb = decLbl;
            NSString  *cap = self.deviceInfo.battery_capacity;
            NSAttributedString *tAttString = [NSAttributedString getAttributeWith:@[@"%",@"V",@"Ah",@"ah",@"km",@"h",@"m",@"°C",@"次"] string:cap Font:Font(32) Color:Black_Color attributeFont:Font(16) attributeColor:Black_Color];
            self.capacityLb.attributedText = tAttString;
        }else{
            self.batteryLb = decLbl;
        }
    }

    if(titleArr.count == 2){
        UIView *hlineView = [UIView setLineViewWithframe:CGRectZero forinView:informationView];
        [hlineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset((DEVICE_WIDTH - 48) / 2 - 0.5);
            make.width.offset(1);
            make.top.offset(24);
            make.bottom.offset(-24);
        }];
    }

    
    UIView *carConditionView = [[UIView alloc] init];
    [_scrollView addSubview:carConditionView];
    [carConditionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.width.offset(DEVICE_WIDTH - 48);
        make.height.offset(156);
        make.top.equalTo(informationView.mas_bottom).offset(20);
    }];
    carConditionView.layer.cornerRadius = 25;
    carConditionView.clipsToBounds = YES;
    carConditionView.backgroundColor = Whire_Color;
    
    UILabel *conditionLbl = [UILabel setLblText:@"当前车况" font:Font(16) withColor:Black_Color inSubView:carConditionView];
    [conditionLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.offset(24);
    }];
    
    [carConditionView addSubview:self.collectionV];
    [_collectionV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.width.equalTo(carConditionView);
        make.height.offset(72);
        make.top.equalTo(carConditionView.mas_top).offset(60);
    }];
    _scrollView.contentSize = CGSizeMake(DEVICE_WIDTH, 450);
}

-(void)refreshUI{
    if(_operationInfo){
        NSString *battery = [NSString stringWithFormat:@"%d%@",[_operationInfo[@"battery_level"] intValue],@"%"];
        NSAttributedString *tAttString = [NSAttributedString getAttributeWith:@[@"%",@"V",@"Ah",@"ah",@"km",@"h",@"m",@"°C",@"次"] string:battery Font:Font(32) Color:Black_Color attributeFont:Font(16) attributeColor:Black_Color];
        self.batteryLb.attributedText = tAttString;
    }
    [self.collectionV reloadData];
}

- (void)getOperationInfo{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:self.deviceInfo.sn_code];
    if([self.deviceInfo is4GDevice]){
        AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
        if( netManger.networkReachabilityStatus != AFNetworkReachabilityStatusNotReachable){
            [self get4GData];
        }else if(p_state == CBPeripheralStateConnected){
            [self getBLEData];
        }
    }else{
        if(p_state == CBPeripheralStateConnected){
            //蓝牙已连接
            [self getBLEData];
        }
    }
    [self checkAndConnectBle];
}


-(void)checkAndConnectBle{
    CBPeripheral *peripheral = [HABleManager checkBleConnectedPeripheral:self.deviceInfo.sn_code];
    if(peripheral){
        if(peripheral.state != CBPeripheralStateConnected){
            DDLogInfo(@"=======bleConnected characteristic is: 09");
            [self bleConnected:peripheral passConnected:YES];
        }
    }else{
        [self bleConnected];
    }
}

-(void)get4GData{
    WEAKSELF
    NSDictionary *parameters = @{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id)};
    [NetworkingTool POST:Device_operation_info parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"data"] isKindOfClass:[NSDictionary class]]){
            weakSelf.operationInfo = response[@"data"];
            [weakSelf refreshUI];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

-(void)getBLEData{
    if(self.deviceInfo.battery_type == 1 || [self.deviceInfo is4GDevice]){
        WEAKSELF
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
        NSMutableDictionary *operate_dict = @{}.mutableCopy;
    //    dispatch_group_enter(group);
    //    dispatch_group_async(group, globalQueue, ^{
    //        DDLogInfo(@"---获取容量。。。");
    //        [HABleManager bleQueryElectrict:^(HABleModel * _Nonnull bleModel) {
    //            int voltage = [bleModel voltage] * 0.1;
    //            int capacity = [bleModel capacity];
    //            NSString *str = [NSString stringWithFormat:@"%dV%dAh",voltage,capacity];
    //            [operate_dict setValue:str forKey:@"battery_capacity"];
    //            DDLogInfo(@"---获取容量成功。。。");
    //            dispatch_group_leave(group);
    //        }];
    //    });
        if(weakSelf.deviceInfo.battery_type == 1){
            dispatch_group_enter(group);
            dispatch_group_async(group, globalQueue, ^{
                DDLogInfo(@"---获取电量。。。");
                [HABleManager bleQueryElectrictStatus:^(HABleModel * _Nonnull bleModel) {
                    int battery_level = [bleModel sos_charge] * 0.1;
                    [operate_dict setValue:@(battery_level) forKey:@"battery_level"];
                    DDLogInfo(@"---获取电量成功。。。");
                    dispatch_group_leave(group);
                }];
            });
        }
        if([weakSelf.deviceInfo is4GDevice]){
            dispatch_group_enter(group);
            dispatch_group_async(group, globalQueue, ^{
                DDLogInfo(@"---获取4G  GPS强度。。。");
                [HABleManager bleQuery4GAndGPS:^(HABleModel * _Nonnull bleModel) {
                    int fourG_signal = [bleModel fourG_signal];
                    int gps_signal = [bleModel gps_signal];
                    [operate_dict setValue:@(fourG_signal) forKey:@"net"];
                    [operate_dict setValue:@(gps_signal) forKey:@"gps"];
                    DDLogInfo(@"---获取4G  GPS强度成功。。。");
                    dispatch_group_leave(group);
                }];
            });
        }
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            weakSelf.operationInfo = operate_dict;
            [weakSelf refreshUI];
            DDLogInfo(@"---全部结束。。。");
        });
    }
}

#pragma mark-noti
-(void)blueVerifySuccess{
    [self getBLEData];
}



- (void)bleConnected:(CBPeripheral *)peripheral passConnected:(BOOL)passConnected{
    if(peripheral.state == CBPeripheralStateConnected || peripheral.state == CBPeripheralStateConnecting){
        return;
    }
    self.connecting = YES;
    [self.collectionV reloadData];
    WEAKSELF
    [[HABleManager sharedManager] connectToPeripheral:peripheral success:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral) {
        weakSelf.connecting = NO;
        [weakSelf.collectionV reloadData];
        if(passConnected){
            [weakSelf getBLEData];
        }
    } fail:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
        [[KRAlartManager shareInstance] showAlert:@"请前往设置查看是否已配对并忽略"];
        weakSelf.connecting = NO;
        [weakSelf.collectionV reloadData];
    } characteristic:^(CBPeripheral * _Nonnull CBPeripheral, CBService * _Nonnull service, NSError * _Nonnull error) {
        
    }];
}

- (void)bleConnected{
    NSString *sn_cond = [UserInfoManager sharedInstance].currentDeviceInfo.sn_code;
    CBPeripheralState state = [HABleManager checkBleConnectedState:sn_cond];
    if(state == CBPeripheralStateConnected || state == CBPeripheralStateConnecting){
        return;
    }
    self.connecting = YES;
    [self.collectionV reloadData];
    WEAKSELF
    [[HABleManager sharedManager] scanPeriperals:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSDictionary<NSString *,id> * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
        if([peripheral.name containsString: [sn_cond substringFromIndex:sn_cond.length-4]]){
            [[HABleManager sharedManager] stopScanPeriperals];
            weakSelf.connecting = NO;
            [weakSelf.collectionV reloadData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                peripheral.snCode = sn_cond;
                [HABleManager sharedManager].currentPeri = peripheral;
                DDLogInfo(@"=======bleConnected characteristic is: 08");
                [weakSelf bleConnected:peripheral passConnected:NO];
            });
        }
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(self.connecting){
            self.connecting = NO;
            [self.collectionV reloadData];
        }
        [[HABleManager sharedManager] stopScanPeriperals];
    });
}

#pragma mark- UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(collectionView.bounds.size.width/(self.dataArray.count * 1.0), 72);
}

#pragma mark- UICollectionViewDataSource
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    KeRenHCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"KeRenHCollectCell" forIndexPath:indexPath];
    SmartItem *item = self.dataArray[indexPath.item];
    cell.imgV.image = [UIImage imageNamed:item.imgName];
    if(item.type == SmartType_Connect_Empty){
        cell.lineV.hidden = YES;
        cell.titleLb.hidden = YES;
        cell.statusLb.hidden = YES;
        cell.img_center_y.constant = 0;
        cell.img_width_c.constant = 107;
    }else{
        if(!self.deviceInfo.deviceConfig.gps && !self.deviceInfo.deviceConfig.fourg){
            cell.lineV.hidden = YES;
        }else{
            cell.lineV.hidden = (indexPath.item == self.dataArray.count-1);
        }
        cell.lineV.backgroundColor = Color_EEEEEE;
        cell.titleLb.hidden = NO;
        cell.titleLb.text = item.title;
        cell.statusLb.hidden = NO;
        cell.statusLb.layer.cornerRadius = 9;
        cell.statusLb.clipsToBounds = YES;
        cell.img_center_y.constant = -5;
        cell.img_width_c.constant = 40;
        CBPeripheralState state = [HABleManager checkBleConnectedState:self.deviceInfo.sn_code];
        if(item.type == SmartType_BlueTooth){
            cell.statusLb.text = self.connecting ? @"  连接中  " : state == CBPeripheralStateConnected ? @"  已连接  " : @"  未连接  ";
            cell.statusLb.backgroundColor = state == CBPeripheralStateConnected ? Color_7ACC00 : Color_FCA35C;
        }else if(item.type == SmartType_GPS){
            cell.statusLb.text =  [_operationInfo[@"gps"] boolValue] ? @"  正常  " : @"  异常  ";
            cell.statusLb.backgroundColor = [_operationInfo[@"gps"] boolValue] ? Color_7ACC00 : Color_FCA35C;
        }else if(item.type == SmartType_4G){
            cell.statusLb.text =  [_operationInfo[@"net"] boolValue] ? @"  正常  " : @"  异常  ";
            cell.statusLb.backgroundColor = [_operationInfo[@"net"] boolValue] ? Color_7ACC00 : Color_FCA35C;
        }
    }
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SmartItem *item = self.dataArray[indexPath.item];
    if(item.type == SmartType_BlueTooth){
        [self checkAndConnectBle];
    }
      
}

@end
